<template>
  <div class="node-properties-panel">
    <div v-if="!nodeConfiguration" class="no-node-selected">
      <div class="placeholder-text">请选择一个节点查看其属性</div>
    </div>

    <div v-else class="properties-container">
      <!-- 节点基本信息 -->
      <div class="node-header">
        <div class="node-title">
          <el-icon><el-icon-setting /></el-icon>
          {{ nodeConfiguration.name }}
        </div>
        <div class="node-category">{{ nodeConfiguration.category }}</div>
      </div>

      <!-- 主折叠面板 -->
      <el-collapse v-model="activeCollapse" class="main-collapse">
        <!-- 属性面板 -->
        <el-collapse-item name="properties" title="属性">
          <template #title>
            <div class="collapse-title">
              <el-icon><el-icon-tools /></el-icon>
              <span>属性</span>
            </div>
          </template>

          <div class="properties-content">
            <!-- 当没有基础属性时显示占位提示 -->
            <div v-if="basicProperties.length === 0" class="no-properties-placeholder">
              <div class="placeholder-icon">
                <el-icon><el-icon-tools /></el-icon>
              </div>
              <div class="placeholder-text">该节点暂无基础属性配置</div>
              <div class="placeholder-hint">基础属性用于配置节点的基本信息</div>
            </div>
            <!-- 动态渲染基础属性 -->
            <div v-for="property in basicProperties" :key="property.key" class="property-item">
              <div class="property-label">
                <span class="label-text">{{ property.label }}</span>
                <el-tooltip v-if="property.description" :content="property.description" effect="dark" :offset="10" placement="top">
                  <el-icon class="help-icon"><el-icon-info-filled /></el-icon>
                </el-tooltip>
                <span v-if="property.required" class="required">*</span>
              </div>
              <div class="property-value">
                <!-- 输入框类型 -->
                <el-input
                  v-if="property.type === 'input'"
                  :model-value="getPropertyValue(property.key)"
                  :placeholder="property.placeholder"
                  size="small"
                  @update:model-value="(value) => onPropertyChange(property.key, value)"
                />
                <!-- 数字输入框类型 -->
                <el-input-number
                  v-else-if="property.type === 'number'"
                  :max="property.max"
                  :min="property.min"
                  :model-value="getPropertyValue(property.key)"
                  size="small"
                  :step="property.step"
                  @update:model-value="(value) => onPropertyChange(property.key, value)"
                />
                <!-- 开关类型 -->
                <el-switch
                  v-else-if="property.type === 'switch'"
                  :model-value="getPropertyValue(property.key)"
                  size="small"
                  @change="(value) => onPropertyChange(property.key, value)"
                />
                <span v-if="property.type === 'switch'" class="property-unit">
                  {{ getPropertyValue(property.key) ? '开' : '关' }}
                </span>
                <!-- 选择框类型 -->
                <el-select
                  v-else-if="property.type === 'select'"
                  :model-value="getPropertyValue(property.key)"
                  size="small"
                  style="width: 100%"
                  @update:model-value="(value) => onPropertyChange(property.key, value)"
                >
                  <el-option v-for="option in property.options" :key="option.value" :label="option.label" :value="option.value" />
                </el-select>
                <!-- 颜色选择器类型 -->
                <el-color-picker
                  v-else-if="property.type === 'color'"
                  :model-value="getPropertyValue(property.key)"
                  size="small"
                  @change="(value) => onPropertyChange(property.key, value)"
                />
                <!-- 文本域类型 -->
                <el-input
                  v-else-if="property.type === 'textarea'"
                  :model-value="getPropertyValue(property.key)"
                  :placeholder="property.placeholder"
                  size="small"
                  type="textarea"
                  @update:model-value="(value) => onPropertyChange(property.key, value)"
                />
              </div>
            </div>
          </div>
        </el-collapse-item>

        <!-- 参数面板 -->
        <el-collapse-item name="parameters" title="参数">
          <template #title>
            <div class="collapse-title">
              <el-icon><el-icon-data-line /></el-icon>
              <span>参数</span>
            </div>
          </template>

          <!-- 参数子折叠面板 -->
          <el-collapse v-model="activeParameterCollapse" class="sub-collapse">
            <!-- 当没有参数组且没有动态参数面板时显示占位提示 -->
            <div v-if="parameterGroups.length === 0 && dynamicParameterPanels.length === 0" class="no-parameters-placeholder">
              <div class="placeholder-icon">
                <el-icon><el-icon-document /></el-icon>
              </div>
              <div class="placeholder-text">该节点暂无可配置参数</div>
              <div class="placeholder-hint">您可以在格式选项卡中调整节点的外观属性</div>
            </div>

            <!-- 动态生成的参数组面板 -->
            <el-collapse-item v-for="group in parameterGroups" :key="group.key" :name="group.key" :title="group.title">
              <div class="parameter-group">
                <div v-if="group.properties.length === 0" class="empty-group-placeholder">
                  <div class="placeholder-text">该参数组暂无配置项</div>
                </div>
                <div v-for="property in group.properties" :key="property.key" class="property-item">
                  <div class="property-label">
                    <span class="label-text">{{ property.label }}</span>
                    <el-tooltip v-if="property.description" :content="property.description" effect="dark" :offset="10" placement="top">
                      <el-icon class="help-icon"><el-icon-info-filled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div class="property-value">
                    <!-- 输入框类型 -->
                    <el-input
                      v-if="property.type === 'input'"
                      :model-value="getParameterValue(group.key, property.key)"
                      :placeholder="property.placeholder"
                      size="small"
                      @update:model-value="(value) => onParameterChange(group.key, property.key, value)"
                    />
                    <!-- 数字输入框类型 -->
                    <el-input-number
                      v-else-if="property.type === 'number'"
                      :max="property.max"
                      :min="property.min"
                      :model-value="getParameterValue(group.key, property.key)"
                      size="small"
                      :step="property.step"
                      @update:model-value="(value) => onParameterChange(group.key, property.key, value)"
                    />
                    <!-- 开关类型 -->
                    <el-switch
                      v-else-if="property.type === 'switch'"
                      :model-value="getParameterValue(group.key, property.key)"
                      size="small"
                      @change="(value) => onParameterChange(group.key, property.key, value)"
                    />
                    <!-- 选择框类型 -->
                    <el-select
                      v-else-if="property.type === 'select'"
                      :model-value="getParameterValue(group.key, property.key)"
                      size="small"
                      style="width: 100%"
                      @update:model-value="(value) => onParameterChange(group.key, property.key, value)"
                    >
                      <el-option v-for="option in property.options" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                    <!-- 颜色选择器类型 -->
                    <el-color-picker
                      v-else-if="property.type === 'color'"
                      :model-value="getParameterValue(group.key, property.key)"
                      size="small"
                      @change="(value) => onParameterChange(group.key, property.key, value)"
                    />
                    <!-- 文本域类型 -->
                    <el-input
                      v-else-if="property.type === 'textarea'"
                      :model-value="getParameterValue(group.key, property.key)"
                      :placeholder="property.placeholder"
                      size="small"
                      type="textarea"
                      @update:model-value="(value) => onParameterChange(group.key, property.key, value)"
                    />
                    <span v-if="getPropertyUnit(property)" class="property-unit">
                      {{ getPropertyUnit(property) }}
                    </span>
                  </div>
                </div>
              </div>
            </el-collapse-item>

            <!-- 动态子面板 -->
            <el-collapse-item
              v-for="dynamicPanel in dynamicParameterPanels"
              :key="dynamicPanel.key"
              :name="dynamicPanel.key"
              :title="dynamicPanel.title"
            >
              <div class="parameter-group">
                <div v-if="dynamicPanel.parameters.length === 0" class="empty-group-placeholder">
                  <div class="placeholder-text">该动态参数组暂无配置项</div>
                </div>
                <div v-for="param in dynamicPanel.parameters" :key="param.key" class="property-item">
                  <div class="property-label">
                    <span class="label-text">{{ param.label }}</span>
                    <el-tooltip v-if="param.description" :content="param.description" effect="dark" :offset="10" placement="top">
                      <el-icon class="help-icon"><el-icon-info-filled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div class="property-value">
                    <el-input
                      v-if="param.type === 'input'"
                      :model-value="getSafeDynamicValue(dynamicPanel.key, param.key)"
                      size="small"
                      @update:model-value="(value) => updateDynamicValue(dynamicPanel.key, param.key, value)"
                    />
                    <el-input-number
                      v-else-if="param.type === 'number'"
                      :max="param.max"
                      :min="param.min"
                      :model-value="getSafeDynamicValue(dynamicPanel.key, param.key)"
                      size="small"
                      @update:model-value="(value) => updateDynamicValue(dynamicPanel.key, param.key, value)"
                    />
                    <el-select
                      v-else-if="param.type === 'select'"
                      :model-value="getSafeDynamicValue(dynamicPanel.key, param.key)"
                      size="small"
                      style="width: 100%"
                      @update:model-value="(value) => updateDynamicValue(dynamicPanel.key, param.key, value)"
                    >
                      <el-option v-for="option in param.options" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                    <span v-if="param.unit" class="property-unit">{{ param.unit }}</span>
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>

        <!-- 引脚面板 - 只在非模块节点时显示 -->
        <el-collapse-item v-if="!nodeConfiguration.isModule" name="pins" title="引脚">
          <template #title>
            <div class="collapse-title">
              <el-icon><el-icon-connection /></el-icon>
              <span>引脚</span>
            </div>
          </template>

          <div class="pins-content">
            <div v-if="nodeConfiguration.pins.length === 0" class="no-pins-placeholder">
              <div class="placeholder-icon">
                <el-icon><el-icon-connection /></el-icon>
              </div>
              <div class="placeholder-text">该节点暂无引脚配置</div>
              <div class="placeholder-hint">引脚配置用于定义节点的输入输出接口</div>
            </div>
            <div v-for="pin in nodeConfiguration.pins" :key="pin.id" class="pin-item">
              <div class="pin-header">
                <div class="pin-label">{{ pin.label }}</div>
                <div class="pin-type" :class="pin.type">
                  {{ pin.type === 'input' ? '输入' : '输出' }}
                </div>
                <div class="pin-position">{{ getPositionLabel(pin.position) }}</div>
              </div>

              <div class="pin-controls">
                <div class="property-item">
                  <div class="property-label">{{ pin.label }}值</div>
                  <div class="property-value">
                    <el-input
                      :model-value="getSafePinValue(pin.id)"
                      :placeholder="`请输入${pin.label}的值`"
                      size="small"
                      @update:model-value="(value) => updatePinValue(pin.id, 'value', value)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>

      <!-- 操作按钮 -->
      <!-- <div class="actions-section">
        <el-button size="small" type="primary" @click="applyChanges">应用更改</el-button>
        <el-button size="small" @click="resetValues">重置</el-button>
      </div>   -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import type { NodeConfiguration, NodeProperty } from '../utils/nodeInfo'

// Props
interface Props {
  nodeConfiguration: NodeConfiguration | null
  selectedNodeId: string | null
  nodeData?: Record<string, any>
  dynamicParameterPanels?: Array<{
    key: string
    title: string
    parameters: Array<{
      key: string
      label: string
      type: 'input' | 'number' | 'select'
      min?: number
      max?: number
      unit?: string
      description?: string
      options?: Array<{ label: string; value: any }>
    }>
  }>
}

const props = withDefaults(defineProps<Props>(), {
  nodeData: () => ({}),
  dynamicParameterPanels: () => [],
})

// Emits
interface Emits {
  (e: 'property-change', data: { key: string; value: any }): void
  (e: 'parameter-change', data: { group: string; key: string; value: any }): void
  (e: 'pin-value-change', data: { pinId: string; type: string; value: any }): void
  (e: 'apply-changes'): void
}

const emit = defineEmits<Emits>()

// 响应式数据
const activeCollapse = ref(['properties', 'parameters', 'pins'])
const activeParameterCollapse = ref<string[]>([])

// 属性值存储
const propertyValues = reactive<Record<string, any>>({})
const parameterValues = reactive<Record<string, Record<string, any>>>({})

// 引脚值
const pinValues = ref<Record<string, string>>({})

// 不再使用硬编码的参数组映射，改为从JSON配置中读取

// 计算属性 - 基础属性（只包含启用和大纲级别）
const basicProperties = computed(() => {
  if (!props.nodeConfiguration) return []

  // 基础属性只包含enabled和level两个属性
  const basicKeys = new Set(['enabled', 'level'])

  return props.nodeConfiguration.properties.filter((prop) => basicKeys.has(prop.key))
})

// 计算属性 - 参数组（从JSON配置中读取分组信息）
const parameterGroups = computed(() => {
  if (!props.nodeConfiguration) return []

  const groups: Array<{
    key: string
    title: string
    collapsed?: boolean
    properties: NodeProperty[]
  }> = []

  // 获取基础属性的键
  const basicKeys = new Set(['enabled', 'level'])

  // 如果节点有参数组配置，按配置分组
  if (props.nodeConfiguration.parameterGroups && Array.isArray(props.nodeConfiguration.parameterGroups)) {
    props.nodeConfiguration.parameterGroups.forEach((groupConfig) => {
      if (groupConfig && groupConfig.key && props.nodeConfiguration?.properties) {
        // 根据group字段过滤属性
        const groupProperties = props.nodeConfiguration.properties.filter((prop) => prop && prop.group === groupConfig.key)

        if (groupProperties.length > 0) {
          groups.push({
            key: groupConfig.key,
            title: groupConfig.title,
            collapsed: groupConfig.collapsed,
            properties: groupProperties,
          })
        }
      }
    })
  } else {
    // 如果节点没有参数组配置，创建默认分组
    // 将除基础属性外的所有属性放入默认的"配置"组
    const nonBasicProperties = props.nodeConfiguration.properties.filter((prop) => !basicKeys.has(prop.key))

    if (nonBasicProperties.length > 0) {
      groups.push({
        key: 'configuration',
        title: 'Configuration',
        collapsed: false,
        properties: nonBasicProperties,
      })
    }
  }

  return groups
})

// 计算属性
const getPositionLabel = (position: string) => {
  const labels: Record<string, string> = {
    left: '左',
    right: '右',
    top: '上',
    bottom: '下',
  }
  return labels[position] || position
}

// 获取属性单位
const getPropertyUnit = (property: NodeProperty) => {
  const unitMapping: Record<string, string> = {
    inductance: 'H',
    capacitance: 'F',
    voltage: 'V',
    resistance: 'Ω',
    tolerance: '%',
    power: 'W',
    powerRating: 'W',
    frequency: 'Hz',
    efficiency: '%',
    ratedCurrent: 'A',
    ratedVoltage: 'V',
    switchingTime: 'ms',
    current: 'A',
    ripple: '%',
    temperature: '°C',
    temperatureCoeff: 'ppm/°C',
    noiseLevel: 'dB',
    esr: 'Ω',
    ratedPower: 'kW',
    currentPower: 'kW',
    leakageCurrent: 'μA',
    rippleCurrent: 'A',
    lifespan: 'hours',
    impedance: 'Ω',
    primaryVoltage: 'V',
    secondaryVoltage: 'V',
    operatingForce: 'N',
    contactResistance: 'mΩ',
    branchCurrent: 'kA',
    branchVoltage: 'kV',
    activePower: 'MW',
    reactivePower: 'MVAr',
    apparentPower: 'MVA',
    phaseAngle: 'deg',
    losses: 'W',
    saturationCurrent: 'A',
    timeStep: 's',
    convergenceTolerance: '',
    strokeWidth: 'px',
    accuracy: '°C',
    samplingRate: 'Hz',
    alarmThreshold: '°C',
    memorySize: 'KB',
    scanTime: 'ms',
    screenSize: '英寸',
    brightness: '%',
    bandwidth: 'Mbps',
    // 太阳能发电机专用单位
    panelArea: 'm²',
    irradiance: 'W/m²',
  }
  return unitMapping[property.key] || ''
}

// 获取属性值
const getPropertyValue = (key: string) => {
  if (propertyValues[key] !== undefined) {
    return propertyValues[key]
  }

  // 从节点数据中获取值（支持嵌套结构）
  if (props.nodeData[key] !== undefined) {
    return props.nodeData[key]
  }

  // 从节点数据的properties中获取值
  if (props.nodeData.properties && props.nodeData.properties[key] !== undefined) {
    return props.nodeData.properties[key]
  }

  // 从配置中获取默认值
  const property = props.nodeConfiguration?.properties.find((p) => p.key === key)
  return property?.defaultValue ?? ''
}

// 获取参数值 - 统一使用扁平化的propertiesData结构
const getParameterValue = (groupKey: string, propertyKey: string) => {
  // 1. 首先检查本地parameterValues（用户当前的编辑状态）
  if (parameterValues[groupKey]?.[propertyKey] !== undefined) {
    return parameterValues[groupKey][propertyKey]
  }

  // 2. 从节点数据的propertiesData中直接获取值（扁平化结构）
  if (props.nodeData.propertiesData && props.nodeData.propertiesData[propertyKey] !== undefined) {
    return props.nodeData.propertiesData[propertyKey]
  }

  // 3. 向后兼容：从节点数据的propertiesData的分组结构中获取值
  if (
    props.nodeData.propertiesData &&
    props.nodeData.propertiesData[groupKey] &&
    props.nodeData.propertiesData[groupKey][propertyKey] !== undefined
  ) {
    return props.nodeData.propertiesData[groupKey][propertyKey]
  }

  // 4. 向后兼容：从节点数据的parameterGroups中获取值
  if (
    props.nodeData.parameterGroups &&
    props.nodeData.parameterGroups[groupKey] &&
    props.nodeData.parameterGroups[groupKey][propertyKey] !== undefined
  ) {
    return props.nodeData.parameterGroups[groupKey][propertyKey]
  }

  // 5. 向后兼容：从节点数据的parameterValues中获取值
  if (
    props.nodeData.parameterValues &&
    props.nodeData.parameterValues[groupKey] &&
    props.nodeData.parameterValues[groupKey][propertyKey] !== undefined
  ) {
    return props.nodeData.parameterValues[groupKey][propertyKey]
  }

  // 6. 向后兼容：从节点数据中直接获取值
  if (props.nodeData[propertyKey] !== undefined) {
    return props.nodeData[propertyKey]
  }

  // 7. 向后兼容：从节点数据的properties中获取值
  if (props.nodeData.properties && props.nodeData.properties[propertyKey] !== undefined) {
    return props.nodeData.properties[propertyKey]
  }

  // 8. 从配置中获取默认值
  const property = props.nodeConfiguration?.properties.find((p) => p.key === propertyKey)
  return property?.defaultValue ?? ''
}

// 安全获取动态参数值
const getSafeDynamicValue = (panelKey: string, paramKey: string) => {
  if (!parameterValues.dynamic) {
    parameterValues.dynamic = {}
  }
  if (!parameterValues.dynamic[panelKey]) {
    parameterValues.dynamic[panelKey] = {}
  }
  return parameterValues.dynamic[panelKey][paramKey] || ''
}

// 更新动态参数值
const updateDynamicValue = (panelKey: string, paramKey: string, value: any) => {
  if (!parameterValues.dynamic) {
    parameterValues.dynamic = {}
  }
  if (!parameterValues.dynamic[panelKey]) {
    parameterValues.dynamic[panelKey] = {}
  }
  parameterValues.dynamic[panelKey][paramKey] = value
  onParameterChange('dynamic', `${panelKey}.${paramKey}`, value)
}

// 安全获取引脚值
const getSafePinValue = (pinId: string): string => {
  // 如果已有值，直接返回（包括用户输入的值）
  if (pinValues.value[pinId] !== undefined) {
    return pinValues.value[pinId]
  }

  // 只有在没有值时才初始化为空字符串
  pinValues.value[pinId] = ''
  return pinValues.value[pinId]
}

// 更新引脚值
const updatePinValue = (pinId: string, type: string, value: string | undefined) => {
  if (value !== undefined) {
    pinValues.value[pinId] = value
    onPinValueChange(pinId, type, value)
  }
}

// 用于跟踪当前节点ID，避免重复初始化
let currentNodeId = ref<string | null>(null)

// 监听节点配置变化，只在真正切换节点时初始化值
watch(
  [() => props.nodeConfiguration, () => props.selectedNodeId],
  ([newConfig, newSelectedNodeId]) => {
    // console.log('NodePropertiesPanel: 节点配置或ID变化', {
    //   nodeId: newSelectedNodeId,
    //   configName: newConfig?.name,
    //   currentNodeId: currentNodeId.value,
    // })

    // 只在真正切换到不同节点时才重新初始化
    const isNewNode = currentNodeId.value !== newSelectedNodeId

    if (newConfig && isNewNode) {
      currentNodeId.value = newSelectedNodeId

      // 初始化属性值
      if (newConfig.properties && Array.isArray(newConfig.properties)) {
        newConfig.properties.forEach((property) => {
          if (!property) return
        // 优先从多个位置获取值
        let value = property.defaultValue
        if (props.nodeData[property.key] !== undefined) {
          value = props.nodeData[property.key]
        } else if (props.nodeData.properties && props.nodeData.properties[property.key] !== undefined) {
          value = props.nodeData.properties[property.key]
        }
        propertyValues[property.key] = value
        })
      }

      // 初始化参数组值
      if (parameterGroups.value && Array.isArray(parameterGroups.value)) {
        parameterGroups.value.forEach((group) => {
          if (!group || !group.key) return
          if (!parameterValues[group.key]) {
            parameterValues[group.key] = {}
          }
          if (group.properties && Array.isArray(group.properties)) {
            group.properties.forEach((property) => {
              if (!property) return
                              // 按照与getParameterValue相同的优先级顺序获取值
          let value = property.defaultValue

          // 优先从propertiesData的扁平化结构获取
          if (props.nodeData.propertiesData && props.nodeData.propertiesData[property.key] !== undefined) {
            value = props.nodeData.propertiesData[property.key]
          }
          // 向后兼容：从propertiesData的分组结构获取
          else if (
            props.nodeData.propertiesData &&
            props.nodeData.propertiesData[group.key] &&
            props.nodeData.propertiesData[group.key][property.key] !== undefined
          ) {
            value = props.nodeData.propertiesData[group.key][property.key]
          }
          // 向后兼容：从parameterGroups获取
          else if (
            props.nodeData.parameterGroups &&
            props.nodeData.parameterGroups[group.key] &&
            props.nodeData.parameterGroups[group.key][property.key] !== undefined
          ) {
            value = props.nodeData.parameterGroups[group.key][property.key]
          }
          // 向后兼容：从parameterValues获取
          else if (
            props.nodeData.parameterValues &&
            props.nodeData.parameterValues[group.key] &&
            props.nodeData.parameterValues[group.key][property.key] !== undefined
          ) {
            value = props.nodeData.parameterValues[group.key][property.key]
          }
          // 向后兼容：从节点数据直接获取
          else if (props.nodeData[property.key] !== undefined) {
            value = props.nodeData[property.key]
          }
          // 向后兼容：从properties获取
          else if (props.nodeData.properties && props.nodeData.properties[property.key] !== undefined) {
            value = props.nodeData.properties[property.key]
          }

          parameterValues[group.key][property.key] = value
            })
          }
        })
      }

      // 更新活跃的子折叠面板 - 根据配置的collapsed属性决定是否默认展开
      activeParameterCollapse.value = [
        ...parameterGroups.value.filter((group) => !group.collapsed).map((group) => group.key),
        ...props.dynamicParameterPanels.map((panel) => panel.key),
      ]

      // 初始化引脚值 - 只在切换节点时设置为空字符串
      const newPinValues: Record<string, string> = {}
      if (newConfig.pins && Array.isArray(newConfig.pins)) {
        newConfig.pins.forEach((pin) => {
          if (pin && pin.id) {
            // 只有在切换到新节点时才重置引脚值，保留用户当前编辑的值
            newPinValues[pin.id] = ''
          }
        })
      }
      pinValues.value = newPinValues

      // 初始化动态参数面板值
      if (!parameterValues.dynamic) {
        parameterValues.dynamic = {}
      }
      props.dynamicParameterPanels.forEach((panel) => {
        if (!parameterValues.dynamic[panel.key]) {
          parameterValues.dynamic[panel.key] = {}
        }
        panel.parameters.forEach((param) => {
          if (parameterValues.dynamic[panel.key][param.key] === undefined) {
            parameterValues.dynamic[panel.key][param.key] = ''
          }
        })
      })
    } else if (!newConfig) {
      // 清空所有值
      currentNodeId.value = null
      Object.keys(propertyValues).forEach((key) => {
        delete propertyValues[key]
      })
      Object.keys(parameterValues).forEach((key) => {
        delete parameterValues[key]
      })
      Object.assign(pinValues.value, {})
    }
  },
  { immediate: true }
)

// 监听节点数据变化，特别是引脚数据
watch(
  () => props.nodeData,
  (newNodeData) => {
    // 只在节点配置初始化时设置引脚值，之后不再覆盖用户输入
    // 这里可以移除强制重置逻辑，允许用户正常输入
  },
  { deep: true }
)

// 监听动态参数面板变化
watch(
  () => props.dynamicParameterPanels,
  (newPanels) => {
    // 更新活跃的子折叠面板 - 根据配置的collapsed属性决定是否默认展开
    activeParameterCollapse.value = [
      ...parameterGroups.value.filter((group) => !group.collapsed).map((group) => group.key),
      ...newPanels.map((panel) => panel.key)
    ]

    // 初始化动态参数值
    if (!parameterValues.dynamic) {
      parameterValues.dynamic = {}
    }
    newPanels.forEach((panel) => {
      if (!parameterValues.dynamic[panel.key]) {
        parameterValues.dynamic[panel.key] = {}
      }
      panel.parameters.forEach((param) => {
        if (parameterValues.dynamic[panel.key][param.key] === undefined) {
          parameterValues.dynamic[panel.key][param.key] = ''
        }
      })
    })
  },
  { immediate: true, deep: true }
)

// 事件处理
const onPropertyChange = (key: string, value: any) => {
  propertyValues[key] = value
  emit('property-change', { key, value })
}

const onParameterChange = (group: string, key: string, value: any) => {
  if (group !== 'dynamic') {
    if (!parameterValues[group]) {
      parameterValues[group] = {}
    }
    parameterValues[group][key] = value
  }

  // 发送事件给父组件，让父组件处理数据同步到节点
  emit('parameter-change', { group, key, value })
}

const onPinValueChange = (pinId: string, type: string, value: any) => {
  emit('pin-value-change', { pinId, type, value })
}

const applyChanges = () => {
  emit('apply-changes')
}

const resetValues = () => {
  if (!props.nodeConfiguration) return

  // 重置属性值为默认值
  if (props.nodeConfiguration.properties && Array.isArray(props.nodeConfiguration.properties)) {
    props.nodeConfiguration.properties.forEach((property) => {
      if (property && property.key) {
        propertyValues[property.key] = property.defaultValue
      }
    })
  }

  // 重置参数组值为默认值
  if (parameterGroups.value && Array.isArray(parameterGroups.value)) {
    parameterGroups.value.forEach((group) => {
      if (!group || !group.key) return
      if (!parameterValues[group.key]) {
        parameterValues[group.key] = {}
      }
      if (group.properties && Array.isArray(group.properties)) {
        group.properties.forEach((property) => {
          if (property && property.key) {
            parameterValues[group.key][property.key] = property.defaultValue
          }
        })
      }
    })
  }

  // 重置动态参数
  if (parameterValues.dynamic) {
    Object.keys(parameterValues.dynamic).forEach((key) => {
      parameterValues.dynamic[key] = {}
    })
  }

  // 重置引脚值为空字符串
  if (props.nodeConfiguration && props.nodeConfiguration.pins && Array.isArray(props.nodeConfiguration.pins)) {
    props.nodeConfiguration.pins.forEach((pin) => {
      if (pin && pin.id) {
        pinValues.value[pin.id] = ''
      }
    })
  }

  emit('apply-changes')
}
</script>

<script lang="ts">
// 添加默认导出以支持默认导入
export default {
  name: 'NodePropertiesPanel',
}
</script>

<style lang="scss" scoped>
.node-properties-panel {
  height: 100%;
  overflow-y: auto;

  .no-node-selected {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;

    .placeholder-text {
      font-size: 14px;
      color: #999;
      text-align: center;
    }
  }

  .properties-container {
    padding: 16px;
  }

  .node-header {
    margin-bottom: 24px;

    .node-title {
      display: flex;
      gap: 8px;
      align-items: center;
      padding-bottom: 8px;
      margin-bottom: 12px;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
    }

    .node-category {
      margin-bottom: 12px;
      font-size: 12px;
      color: #909399;
    }
  }

  .main-collapse {
    border: none;

    :deep(.el-collapse-item__header) {
      padding-left: 0;
      background-color: transparent;
      border-bottom: 1px solid #ebeef5;

      .collapse-title {
        display: flex;
        gap: 8px;
        align-items: center;
        font-size: 14px;
        font-weight: 600;
        color: #303133;
      }
    }

    :deep(.el-collapse-item__content) {
      padding-bottom: 16px;
    }

    .properties-content,
    .pins-content {
      padding: 16px 0;
    }

    .property-item {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      .property-label {
        display: flex;
        align-items: center;
        margin-bottom: 6px;
        font-size: 13px;
        color: #606266;

        .label-text {
          margin-right: 4px;
        }

        .help-icon {
          margin-right: 4px;
          font-size: 12px;
          color: #909399;
          cursor: help;
          transition: color 0.2s;

          &:hover {
            color: #409eff;
          }
        }

        .required {
          margin-left: 4px;
          color: #f56c6c;
        }
      }

      .property-value {
        display: flex;
        gap: 8px;
        align-items: center;
        width: 100%;

        .property-unit {
          min-width: 20px;
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .pin-item {
      padding: 12px;
      margin-bottom: 12px;
      background-color: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 6px;

      &:last-child {
        margin-bottom: 0;
      }

      .pin-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8px;

        .pin-label {
          font-size: 13px;
          font-weight: 500;
          color: #303133;
        }

        .pin-type {
          padding: 2px 6px;
          font-size: 11px;
          border-radius: 3px;

          &.input {
            color: #409eff;
            background-color: #e8f4fd;
          }

          &.output {
            color: #67c23a;
            background-color: #f0f9ff;
          }
        }

        .pin-position {
          font-size: 11px;
          color: #909399;
        }
      }

      .pin-controls {
        .property-item {
          margin-bottom: 8px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }

  .sub-collapse {
    border: none;

    :deep(.el-collapse-item__header) {
      padding-left: 20px;
      font-size: 13px;
      background-color: #f8f9fa;
      border-bottom: 1px solid #e9ecef;
    }

    :deep(.el-collapse-item__content) {
      padding: 12px 20px;
      background-color: #fafafa;
    }

    .parameter-group {
      .property-item {
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .actions-section {
    display: flex;
    gap: 8px;
    padding-top: 16px;
    margin-top: 24px;
    border-top: 1px solid #ebeef5;
  }

  // 占位提示样式
  .no-properties-placeholder,
  .no-parameters-placeholder,
  .no-pins-placeholder,
  .empty-group-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 32px 16px;
    color: #999;
    text-align: center;

    .placeholder-icon {
      margin-bottom: 12px;
      font-size: 32px;
      color: #d3d4d6;
    }

    .placeholder-text {
      margin-bottom: 8px;
      font-size: 14px;
      font-weight: 500;
      color: #909399;
    }

    .placeholder-hint {
      font-size: 12px;
      line-height: 1.4;
      color: #c0c4cc;
    }
  }

  .empty-group-placeholder {
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 4px;

    .placeholder-text {
      margin-bottom: 0;
      font-size: 13px;
    }
  }
}

// Element Plus 样式覆盖
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-color-picker) {
  .el-color-picker__trigger {
    width: 100%;
    height: 28px;
  }
}

:deep(.el-switch) {
  --el-switch-height: 20px;
}

:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item__header) {
  height: auto;
  padding: 12px 0;
  line-height: 1.5;
}

:deep(.el-collapse-item__wrap) {
  border-bottom: none;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 12px;
}
</style>
